import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/keyboard_utils.dart';

/// Flutter本地存储示例
class LocalStorageExample extends StatefulWidget {
  const LocalStorageExample({super.key});

  @override
  State<LocalStorageExample> createState() => _LocalStorageExampleState();
}

class _LocalStorageExampleState extends State<LocalStorageExample> {
  final _keyController = TextEditingController();
  final _valueController = TextEditingController();
  String _result = '';
  List<String> _storedKeys = [];

  @override
  void initState() {
    super.initState();
    _loadStoredKeys();
  }

  @override
  void dispose() {
    _keyController.dispose();
    _valueController.dispose();
    super.dispose();
  }

  // 加载所有存储的键
  Future<void> _loadStoredKeys() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _storedKeys = prefs.getKeys().toList();
    });
  }

  // 保存字符串
  Future<void> _saveString() async {
    final key = _keyController.text;
    final value = _valueController.text;

    if (key.isEmpty || value.isEmpty) {
      setState(() {
        _result = '请输入键和值';
      });
      return;
    }

    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(key, value);

    setState(() {
      _result = '已保存: $key = $value';
    });
    _loadStoredKeys();
  }

  // 读取字符串
  Future<void> _loadString() async {
    final key = _keyController.text;

    if (key.isEmpty) {
      setState(() {
        _result = '请输入键名';
      });
      return;
    }

    final prefs = await SharedPreferences.getInstance();
    final value = prefs.getString(key);

    setState(() {
      if (value != null) {
        _result = '读取成功: $key = $value';
      } else {
        _result = '未找到键: $key';
      }
    });
  }

  // 删除数据
  Future<void> _deleteData() async {
    final key = _keyController.text;

    if (key.isEmpty) {
      setState(() {
        _result = '请输入要删除的键名';
      });
      return;
    }

    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(key);

    setState(() {
      _result = '已删除: $key';
    });
    _loadStoredKeys();
  }

  // 清除所有数据
  Future<void> _clearAll() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.clear();

    setState(() {
      _result = '已清除所有数据';
    });
    _loadStoredKeys();
  }

  // 保存不同类型
  Future<void> _saveMultipleTypes() async {
    final prefs = await SharedPreferences.getInstance();

    await prefs.setString('username', '张三');
    await prefs.setInt('age', 25);
    await prefs.setDouble('score', 95.5);
    await prefs.setBool('isVip', true);
    await prefs.setStringList('hobbies', ['读书', '运动', '旅游']);

    setState(() {
      _result = '''
已保存多种类型的数据：
• String: username = 张三
• int: age = 25
• double: score = 95.5
• bool: isVip = true
• List<String>: hobbies = [读书, 运动, 旅游]
      ''';
    });
    _loadStoredKeys();
  }

  // 读取所有数据
  Future<void> _loadAllData() async {
    final prefs = await SharedPreferences.getInstance();
    final keys = prefs.getKeys();

    if (keys.isEmpty) {
      setState(() {
        _result = '没有存储的数据';
      });
      return;
    }

    StringBuffer buffer = StringBuffer('所有存储的数据:\n\n');

    for (final key in keys) {
      final value = prefs.get(key);
      buffer.writeln('$key: $value');
    }

    setState(() {
      _result = buffer.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    return DismissKeyboardScaffold(
      appBar: AppBar(title: const Text('Flutter 本地存储'), backgroundColor: Theme.of(context).colorScheme.inversePrimary),
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 说明卡片
            Card(
              color: Colors.orange.shade50,
              child: const Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('💾 本地存储概述', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    SizedBox(height: 8),
                    Text(
                      'Flutter本地存储方案：\n'
                      '• SharedPreferences：键值对存储\n'
                      '• 文件存储：读写文件\n'
                      '• SQLite：本地数据库\n'
                      '• Hive/ObjectBox：NoSQL数据库',
                      style: TextStyle(fontSize: 14),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // SharedPreferences基础操作
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('SharedPreferences（键值对存储）', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 12),
                    TextField(
                      controller: _keyController,
                      decoration: const InputDecoration(labelText: '键（Key）', border: OutlineInputBorder(), hintText: '例如: username'),
                    ),
                    const SizedBox(height: 12),
                    TextField(
                      controller: _valueController,
                      decoration: const InputDecoration(labelText: '值（Value）', border: OutlineInputBorder(), hintText: '例如: 张三'),
                    ),
                    const SizedBox(height: 16),
                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: [
                        FilledButton.icon(onPressed: _saveString, icon: const Icon(Icons.save), label: const Text('保存')),
                        FilledButton.icon(onPressed: _loadString, icon: const Icon(Icons.download), label: const Text('读取')),
                        OutlinedButton.icon(onPressed: _deleteData, icon: const Icon(Icons.delete), label: const Text('删除')),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 代码示例
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('代码示例', style: TextStyle(fontWeight: FontWeight.bold)),
                    const SizedBox(height: 8),
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(8)),
                      child: const Text('''import 'package:shared_preferences/shared_preferences.dart';

// 保存数据
Future<void> saveData() async {
  final prefs = await SharedPreferences.getInstance();
  
  await prefs.setString('username', '张三');
  await prefs.setInt('age', 25);
  await prefs.setDouble('score', 95.5);
  await prefs.setBool('isVip', true);
  await prefs.setStringList('tags', ['A', 'B']);
}

// 读取数据
Future<void> loadData() async {
  final prefs = await SharedPreferences.getInstance();
  
  String? username = prefs.getString('username');
  int? age = prefs.getInt('age');
  double? score = prefs.getDouble('score');
  bool? isVip = prefs.getBool('isVip');
  List<String>? tags = prefs.getStringList('tags');
}

// 删除数据
Future<void> deleteData() async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.remove('username');
}

// 清除所有
Future<void> clearAll() async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.clear();
}''', style: TextStyle(fontFamily: 'monospace', fontSize: 10)),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 批量操作
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('批量操作', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 12),
                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: [
                        ElevatedButton.icon(
                          onPressed: _saveMultipleTypes,
                          icon: const Icon(Icons.library_add),
                          label: const Text('保存多种类型'),
                        ),
                        ElevatedButton.icon(onPressed: _loadAllData, icon: const Icon(Icons.list), label: const Text('查看所有数据')),
                        ElevatedButton.icon(
                          onPressed: () async {
                            await _clearAll();
                            if (mounted) {
                              ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('所有数据已清除')));
                            }
                          },
                          icon: const Icon(Icons.clear_all),
                          label: const Text('清除所有'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 存储的键列表
            if (_storedKeys.isNotEmpty)
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text('当前存储的键', style: TextStyle(fontWeight: FontWeight.bold)),
                      const SizedBox(height: 8),
                      Wrap(
                        spacing: 8,
                        children: _storedKeys.map((key) {
                          return Chip(
                            label: Text(key),
                            onDeleted: () async {
                              final prefs = await SharedPreferences.getInstance();
                              await prefs.remove(key);
                              _loadStoredKeys();
                            },
                          );
                        }).toList(),
                      ),
                    ],
                  ),
                ),
              ),

            // 结果显示
            if (_result.isNotEmpty)
              Card(
                color: Colors.green.shade50,
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Row(
                        children: [
                          Icon(Icons.info, color: Colors.green),
                          SizedBox(width: 8),
                          Text('操作结果', style: TextStyle(fontWeight: FontWeight.bold)),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Text(_result),
                    ],
                  ),
                ),
              ),
            const SizedBox(height: 16),

            // 注意事项
            Card(
              color: Colors.amber.shade50,
              child: const Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('⚠️ 注意事项：', style: TextStyle(fontWeight: FontWeight.bold)),
                    SizedBox(height: 8),
                    Text('• 适合存储简单的键值对'),
                    Text('• 不适合存储大量数据'),
                    Text('• 数据不加密，不要存储敏感信息'),
                    Text('• 支持的类型：String, int, double, bool, List<String>'),
                    Text('• iOS存储在NSUserDefaults'),
                    Text('• Android存储在SharedPreferences'),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 其他存储方案
            Card(
              color: Colors.purple.shade50,
              child: const Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('其他存储方案：', style: TextStyle(fontWeight: FontWeight.bold)),
                    SizedBox(height: 8),
                    Text('• path_provider + dart:io - 文件读写'),
                    Text('• sqflite - SQLite本地数据库'),
                    Text('• hive - 轻量级NoSQL数据库'),
                    Text('• objectbox - 高性能对象数据库'),
                    Text('• flutter_secure_storage - 加密存储'),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
